package org.zhq.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.zhq.Const;
import org.zhq.mapper.CarouselMapper;
import org.zhq.pojo.Carousel;
import org.zhq.service.CarouselService;

import java.util.List;

@Service
public class CarouselServiceImpl implements CarouselService {
    private final CarouselMapper carouselMapper;
    private final StringRedisTemplate redisTemplate;

    @Autowired
    public CarouselServiceImpl(CarouselMapper carouselMapper, StringRedisTemplate redisTemplate) {
        this.carouselMapper = carouselMapper;
        this.redisTemplate = redisTemplate;
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public List<Carousel> queryAll(Integer isShow) {
        String carouselStr = redisTemplate.opsForValue().get(Const.Redis.CAROUSEL + ":" + isShow);
        List<Carousel> list;
        if (StrUtil.isBlank(carouselStr)) {
            LambdaQueryWrapper<Carousel> condition = Wrappers.<Carousel>lambdaQuery().eq(Carousel::getIsShow, isShow).orderByDesc(Carousel::getSort);
            list = carouselMapper.selectList(condition);
            redisTemplate.opsForValue().set(Const.Redis.CAROUSEL + ":" + isShow, JSONUtil.toJsonStr(list));
        } else {
            list = JSONUtil.toList(JSONUtil.parseArray(carouselStr), Carousel.class);
        }
        return list;
    }
}
